package eva.savant.core

import eva.savant.businessobject.ad.Rol
import eva.savant.businessobject.ad.UsuarioRol
import eva.savant.businessobject.ad.Sistema
import eva.savant.businessobject.ad.Usuario
import eva.savant.businessobject.gl.Sociedad
import eva.savant.core.navigation.Controller
import eva.savant.core.navigation.Builder
import eva.savant.core.service.NameService
import eva.savant.core.view.util.FacesUtils
import eva.savant.core.view.Base
import eva.savant.core.view.Bean

import org.springframework.security.authentication.*
import org.springframework.security.core.context.*
import javax.faces.context.FacesContext
import javax.faces.bean.SessionScoped
import javax.faces.bean.ManagedBean
import javax.annotation.PostConstruct

@ManagedBean
@SessionScoped
public class CoreBean {

  String username= 'admin'
  
  String password

  Sistema sistema

  Usuario usuario

  Sociedad sociedad

  List lsSistema

  List lsTransaccion

  String  theme= 'sap'

  TreeMap themes= ['Aristo'        : 'aristo',
                   'Pepper-Grinder': 'pepper-grinder',
                   'Excite-Bike'   : 'excite-bike',
                   'Le-Frog'       : 'le-frog',
                   'Trontastic'    : 'trontastic',
                   'UI-Lightness'  : 'ui-lightness',
                   'Sap'           : 'sap',
                   'Sam'           : 'sam']

  def LOGON= 'login?faces-redirect=true'

  def HOME = 'application?faces-redirect=true'

  @PostConstruct
  public void init() { try {

    sociedad= new Sociedad(); sociedad.id= 'CB'

  } catch (Exception e) { FacesUtils.addErrorMessage e } }

  def build() throws Exception {

    sociedad= Base.get(Sociedad.class,sociedad.id)


    def properties = new Properties()

    properties.load(this.class.classLoader.getResourceAsStream('application.properties'))

    sistema= Base.get(Sistema.class,sociedad.id+properties.getProperty('application.id'))


    usuario= Base.get(Usuario.class,'username=? and sociedadId=?',username, sociedad.id)

    def lsRol= (List<Rol>) Base.find(UsuarioRol.class,'rol : usuario.id=? and rol.sistema.id=?', usuario.id, sistema.id)


    if(lsRol?.size() < 1) { message 'El usuario no tiene asignado Rol en este sistema'; return null }


    lsSistema= Base.find(UsuarioRol.class,'rol.sistema : usuario.id=? and rol.sistema.operacionId > 0', usuario.id)


    def navigationBuilder= (Builder) FacesUtils.getManagedBean(NameService.NAVIGATION_BUILDER)

    navigationBuilder.buildMenuTree(lsRol)


    loadDef()


    usuario.inicio= new java.sql.Timestamp(new Date().time)

    usuario.ip= FacesUtils.servletRequest.remoteAddr


    FacesUtils.getHttpSession(false).setAttribute('open-usr-DATE',Bean.toDate(usuario.inicio.time,'dd.MM.yyyy HH:mm'))

    FacesUtils.getHttpSession(false).setAttribute('open-usr-ID',usuario.username)

    FacesUtils.getHttpSession(false).setAttribute('open-usr-IP',usuario.ip)


    merge(usuario)


    def val= FacesUtils.getRequestParameter('exp')


    if(val == null || val.length() < 6) return HOME

    def value= val.split('-')
      

    def controller= (Controller) FacesUtils.getManagedBean(NameService.CONTROLLER)

    controller.transactionId= new Integer(value[0])

    controller.parameter= value[1]

    return HOME
  }


  public String openSession() { try {

    if (username?.length() < 1 && password?.length() < 1) {

    def usr= FacesUtils.getRequestParameter('usr'); username= usr != null && usr.length() > 2? usr : null

    def psd= FacesUtils.getRequestParameter('psd'); password= psd != null && psd.length() > 2? psd : null }


    if (username?.length() < 1 || password?.length() < 1 || sociedad?.id?.length() < 1) return null


    def authentication= new UsernamePasswordAuthenticationToken(username,password); authentication.details=sociedad.id

    def authManager= (AuthenticationManager) FacesUtils.getSpringBean('authenticationManager')

    def authResponseToken= authManager.authenticate(authentication)
  
    SecurityContextHolder.context.authentication= authResponseToken
  
  
    if (authResponseToken.isAuthenticated())
  
      if (usuario == null) return build()
  
      else if(usuario.username.equalsIgnoreCase(username)) return HOME

      else { FacesUtils.addErrorMessage 'Debe cerrar la session ' + usuario.username +
  
             ' en este navegador para ingresar con otra cuenta usuario'; return HOME }
  
    else message 'El usuario o el password es incorrecto, porfavor intente nuevamente.'

    return null

  } catch (Exception e) { FacesUtils.addErrorMessage e; return null } }


  def closeSession() { try {

    usuario= Base.get(Usuario.class,usuario.id)

    usuario.fin= new java.sql.Timestamp(new Date().time); merge(usuario)

    saveDef()

    FacesContext.currentInstance.externalContext.invalidateSession()

    return LOGON

  } catch (Exception e) { FacesUtils.addErrorMessage e; return null } }


  public <T> T merge(T entity) throws Exception { return Base.entityService.merge(entity) }


  public void message(String msg) throws Exception { FacesUtils.addErrorMessage msg }


  public void loadDef() throws Exception {

    def usrRol= Base.get(UsuarioRol.class,'usuario.id=? and rol.sistema.id=?',usuario.id,sistema.id)


    theme= usrRol.theme != null && usrRol.theme.length() > 0 ? usrRol.theme : 'sap'


    def r= FacesContext.currentInstance.application.resourceHandler.createResource('theme.css','primefaces-'+theme)

    if(r == null) theme= 'sap'


    def controller= (Controller) FacesUtils.getManagedBean(NameService.CONTROLLER)

    controller.transactionId= usrRol.idTransaccion


    lsTransaccion= new ArrayList()

    lsTransaccion.add 101

    lsTransaccion.add 102

    lsTransaccion.add 103

    lsTransaccion.add 104

    lsTransaccion.add 105

  }


  public void saveDef() throws Exception {

    def usrRol= Base.get(UsuarioRol.class,'usuario.id=? and rol.sistema.id=?',usuario.id,sistema.id)

    def controller= (Controller) FacesUtils.getManagedBean(NameService.CONTROLLER)

    usrRol.idTransaccion= controller.transactionId; merge(usrRol)
  }


  public void saveTheme() throws Exception {

    def usrRol= Base.get(UsuarioRol.class,'usuario.id=? and rol.sistema.id=?',usuario.id, sistema.id)

    usrRol.theme= theme; merge(usrRol)
  }

}